package smartcase.base.auth;

import com.google.common.base.Strings;
import java.util.stream.Stream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public interface AbstractCookieCredentialFunction extends AbstractCredentialFunction {

  String getCookieName();

  default Credential verify(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null || cookies.length == 0) return Credential.INVALID_CREDENTIAL;
    return Stream.of(cookies)
        .filter(cookie -> getCookieName().equals(cookie.getName()))
        .findFirst()
        .map(cookie -> this.mapCookieToCredential(request, cookie))
        .orElse(Credential.INVALID_CREDENTIAL);
  }

  /**
   * @param cookie restdoc.web.base on {@link Cookie} map to CREDENTIAL object instance
   * @param request request obj
   */
  Credential mapCookieToCredential(HttpServletRequest request, Cookie cookie);
}
